﻿using System;
using Unity.Entities;
using Unity.Entities.Content;
using Unity.Entities.Serialization;
using Unity.Scenes;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameStarter : MonoBehaviour
{
    public string remoteUrlRoot;
    public string initialContentSet;

    void Start()
    {
#if ENABLE_CONTENT_DELIVERY
        ContentDeliveryGlobalState.LogFunc = (txt) =>
        {
            Debug.Log("-------- " + txt);
        };
        ContentDeliveryGlobalState.Initialize(remoteUrlRoot, Application.persistentDataPath + "/content-cache", initialContentSet, s =>
        {
            if (s >= ContentDeliveryGlobalState.ContentUpdateState.ContentReady)
                LoadMainScene();
        });
#else
            LoadMainScene();
#endif
    }

    private void Update()
    {
#if ENABLE_CONTENT_DELIVERY && UNITY_EDITOR
        ContentDeliveryGlobalState.Update();
#endif
    }

    void LoadMainScene()
    {
        //content is ready here...
        //SceneManager.LoadScene("SampleScene", LoadSceneMode.Single);

        WorldUnmanaged world = World.DefaultGameObjectInjectionWorld.Unmanaged;
        SystemHandle systemHandle = world.GetExistingUnmanagedSystem<TestPrefabSystem>();
        if (world.EntityManager.HasComponent<LoadMainSceneComplete>(systemHandle))
        {
            world.EntityManager.SetComponentData(systemHandle, new LoadMainSceneComplete()
            {
                isLoaded = true
            });
        }
        else
        {
            world.EntityManager.AddComponentData(systemHandle, new LoadMainSceneComplete()
            {
                isLoaded = true
            });
        }
    }
}
